#!/usr/bin/env python
# _*_ coding:utf-8 _*_

'''
'''

import re
import pandas as pd
import shlex
import collections

def getStatementContent(statement, getComment=False, valNone='x ', separator='//'):
    '''
    valNone: False, 如果没有comment，返回空''，字符串valNone，返回：valNone+statement
    '''
    if not isinstance(statement, str):
        if (getComment):
            if isinstance(valNone, str):
                return 0, valNone + str(statement)
            else:
                return 0, ''
        else:
            return 0, str(statement)

    try:
        lex = shlex.shlex(statement)
        lex.quotes = '\'"'
        lex.whitespace_split = True
        s_list = list(lex)
    except (BaseException) as exc:
        return 1, str(exc)

    pos = -1
    statement_ = statement
    for s_ in s_list:
        if ((s_[0] != '"') and (s_[0] != "'")):
            pos = s_.find(separator)
            if (pos >= 0):
                pos1 = statement_.find(s_)
                pos += pos1
                break
        else:
            statement_ = statement_.replace(s_, ' '*len(s_), 1)

    if (pos >= 0):
        if (getComment):
            return 0, statement[pos+len(separator):].strip()
        else:
            return 0, statement[0:pos].strip()

    if (getComment):
        if isinstance(valNone, str):
            return 2, valNone + statement
        else:
            return 2, ''
    else:
        return 0, statement


def isEmpty(obj):
    if isinstance(obj, pd.core.frame.DataFrame):
        if obj.empty:
            return True
        return False

    if isinstance(obj, collections.Sequence):
        if (len(obj) == 0):
            return True
        else:
            return False

    if obj is None:
        return True
    return False


def listGet(lst, i, defVal=None):
    try:
        return lst[i]
    except (BaseException) as exc:
        return defVal


def getToken(str0, pos):
    len0 = len(str0)
    start = -1
    while (pos < len0):
        if not (str0[pos] in ',\0 \t\r\n\x85\u2028\u2029'):
            start = pos
            break
        pos += 1
    if (start >= 0):
        i = start
        while (i < len0):
            if str0[i] in ',\0 \t\r\n\x85\u2028\u2029':
                return i, str0[start:i]
            i += 1
    else:
        return -1, ''

    return len0, str0[start:]


def safePythonStr(str_):
    return str_.replace('"""', '\"\"\"').replace("'''", '\'\'\'')


def readFile(sr_filename, parameters={}):
    try:
        with open(sr_filename, 'r', encoding = 'utf-8') as f:
            if parameters:
                retStr = ''
                for line in f:
                    try:
                        retStr += line.format(**parameters)
                    except:
                        retStr += line
                return 0, retStr
            else:
                return 0, f.read()
    except (BaseException) as exc:
        return 2, exc


def strsFormatWithLineno(str_):
    if not str_:
        return ''

    retStr = ''
    for (num, value) in enumerate(str_.split('\n')):
        retStr += ("{:>4d}".format(num+1) + " " + value + '\n')
    return retStr


def addNoise(str_, num):
    return '\0' + str(num) + '\0' + str_


def removeNoise(str_):
    if (str_[0] == '\0'):
        i = 1
        len_ = len(str_)
        while (i < len_):
            if (str_[i] == '\0'):
                return str_[i+1:]
            i += 1
    return str_


def strReplaceWords(str_, reg_, dict_):
    '''
    根据字典把一个字符串中的内容做替换
    '''
    def replacement(matchobj):
        key = matchobj.group(0)
        return dict_.get(key, key)

    str0 = re.sub(reg_, replacement, str_)
    return str0


def _strips(direction, text, remove):
    if isinstance(remove, (list, tuple)):
        for subr in remove:
            text = _strips(direction, text, subr)
        return text

    if direction == 'l':
        if text.startswith(remove):
            return text[len(remove):]
    elif direction == 'r':
        if text.endswith(remove):
            return text[:-len(remove)]
    else:
        raise (ValueError, "Direction needs to be r or l.")
    return text


def rstrips(text, remove):
    """
    removes the string `remove` from the right of `text`

        >>> rstrips("foobar", "bar")
        'foo'

    """
    return _strips('r', text, remove)


def lstrips(text, remove):
    """
    removes the string `remove` from the left of `text`

        >>> lstrips("foobar", "foo")
        'bar'
        >>> lstrips('http://foo.org/', ['http://', 'https://'])
        'foo.org/'
        >>> lstrips('FOOBARBAZ', ['FOO', 'BAR'])
        'BAZ'
        >>> lstrips('FOOBARBAZ', ['BAR', 'FOO'])
        'BARBAZ'

    """
    return _strips('l', text, remove)


def strips(text, remove):
    """
    removes the string `remove` from the both sides of `text`

        >>> strips("foobarfoo", "foo")
        'bar'

    """
    return rstrips(lstrips(text, remove), remove)


if __name__ == '__main__':

    text = '1239$ <-> # 4800'
    dict_ = {'$' : '_tong_', '#' : '_ji_'}
    print (strReplaceWords(text, r"\D", dict_))

    str_ = addNoise('this is a test', 1)
    print (str_)
    print (removeNoise(str_))

    pos, s = getToken(' this', 0)
    print ('[' + s + ']')

    s = r'''T\'h 's中华人民共和国tr//ing'is<> > + - s中华人民共和国tr/;/ing has "some double quotes" and 'some single quotes'.'''
    print (getStatementContent(s, separator=';'))
